package com.example.mardan_demo1.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class IpUtils {

    public static String getClientIp(HttpServletRequest request) {
        // 1. 处理代理头（按优先级检查）
        List<String> headers = Arrays.asList(
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_CLIENT_IP",
                "HTTP_X_FORWARDED_FOR"
        );

        String ip = headers.stream()
                .map(request::getHeader)
                .filter(headerIp -> headerIp != null && !headerIp.isEmpty() && !"unknown".equalsIgnoreCase(headerIp))
                .findFirst()
                .orElse(request.getRemoteAddr());

        // 2. 处理多个IP的情况（如 X-Forwarded-For: client, proxy1, proxy2）
        if (ip.contains(",")) {
            ip = Arrays.stream(ip.split(","))
                    .map(String::trim)
                    .filter(IpUtils::isValidIpv4)  // 优先选择IPv4地址
                    .findFirst()
                    .orElse(ip.split(",")[0].trim());
        }

        // 3. 转换IPv6环回地址为IPv4
        if (ip.equals("0:0:0:0:0:0:0:1") || ip.equals("::1")) {
            ip = "127.0.0.1";
        }

        return ip;
    }

    // 验证是否为有效IPv4地址
    private static boolean isValidIpv4(String ip) {
        return ip.matches("^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
    }
}